import util from '../../common/js/util'
import NProgress from 'nprogress'
import axios from 'axios';
import moment from 'moment'
import clothesSizeType from '../../../models/dict/clothesSizeType';
import flowNodeList from '../flow/flowNodeList.vue'
import customerOrderShow from './customerOrderShow.vue'
import taskInfo from '../task/taskInfo.vue'

const dCustomerOrder = require('../../../models/dict/customerOrder');
import flowNode from '../flow/flowNode.vue'


import colorSizeData from './colorSizeData.vue'

import imgSel from '../ui/imgSel.vue'
import Vue from 'vue'


import task from "../../../models/dict/task"

import webPy from '../../../models/comm/webPy';
import file from '../../common/file.vue';
import offerPrint from './offerPrint.vue';
import technologyPrint from './technologyPrint.vue';

export default {
    data() {
        return {
            search: {
                name: ''
            },
            unitArray: clothesSizeType.unitArray(),
            customerOrderList: [],
            clothesSizeTypeArray: clothesSizeType.getTypeArray(),
            allSizeArray: clothesSizeType.sizeArray(),
            total: 0,
            page: 1,
            currCustomerOrderId: "",
            listLoading: false,

            //编辑界面数据1
            ShowSave: false,

            //新增界面数据

            currObj: {

                name: "",
                customerId: "",
                classId: "",
                flow: {

                    nodeList: []
                },
                proof: {
                    sizeIdArray: []
                },
                bulk: {
                    sizeIdArray: []
                },
                fileList: []


            },
            currTab: "1",
            totalPage: 1,
            loading: true,
            customerSelList: [],
            showAddProofColor: false,
            currNodeObj: {},
            editLoading: false,
            ShowSaveNode: false,
            tabs: [{

                title: "测试",
                name: "50"

            }],
            currFlow: {},
            customerName: "",
            showCustomerOrderId: "",
            show1: true,
            showTaskInfo: false,
            task: {},
            taskList: [],
            showOfferPrint: false,
            currFlowClassId: "",
            showTechnologyPrint: false




        }
    },
    methods: {
        afterSaveTask(res) {
            this.showTaskInfo = false
            this.getCustomerOrder()
        },
        toSaveTask(_task) {
            this.task = _task

            this.task.detail = task.fmtSizeDetail(this.task, this.currObj);
            this.showTaskInfo = true


        },

        selFile(file) {

        },

        getUnitArray() {
            return clothesSizeType.unitArray()
        },

        RemoveColor(row) {



            var newColorArray = [];

            this.currObj.colorArray.forEach(function (colorName) {


                if (colorName != row.colorName) {
                    newColorArray.push(colorName);
                }

            }, this);

            this.currObj.colorArray = newColorArray;
            this.sizeChange();

        },

        fileUp(res, file, fileList) {


            this.currObj.fileList.push({

                name: res.file.name,
                url: res.file.url

            });


            if (this.currObj.fileList.length > 0) {


                var hasDefault = false
                this.currObj.fileList.forEach(function (file) {
                    if (file.isDefault) {
                        hasDefault = true
                    }

                }, this);

                if (!hasDefault) {
                    this.currObj.fileList[0].isDefault = true
                }
            }
        },

        handlePreview() { },
        fileRemove(file, fileList) {



            this.currObj.fileList = fileList

        },
        countItemData(item) {


            return dCustomerOrder.countItemData(item);
        },

        handleClose: function (tag, tags) {

            tags.splice(tags.indexOf(tag), 1);
        },
        selSalesMember(o) {

            var b = false;
            this.currObj.salesMembers.forEach(function (manager) {
                if (o._id == manager._id) {

                    b = true;
                    return false;
                }

            }, this);
            if (!b) {
                this.currObj.salesMembers.push({

                    name: o.name,
                    _id: o._id
                });

            }

        },
        getSalesMembers(salesMembers) {
            return dCustomerOrder.getSalesMembers(salesMembers)

        },

        querySearchMember: async function (query, cb) {
            var data = {
                "$or": [
                    { name: { $regex: query } },
                    { namePy: { $regex: await webPy.firstLetter(query) } }
                ]
            }
            //  console.log(JSON.stringify(data));
            if (query !== '') {
                this.loading = true;
                axios.post("/a", {
                    class: "member",
                    para: "getMemberList",
                    j: {
                        data: data

                    }

                }).then((res) => {

                    this.loading = false;

                    var list = res.data.list;

                    list.forEach(function (member) {
                        member.value = member.name;

                    }, this);
                    cb(list)

                });

            }
        },


        tabClick(e) { },
        fmtDate(date) {
            return moment(date).toString("YYYY-MM-DD HH:mm");

        },
        getModelNo(c) {
            return dCustomerOrder.getModelNo(c)

        },
        selCustomer(o) {
            //  console.log(o.value);
            this.currObj.customerName = o.value;
            this.currObj.customerId = o._id;
        },

        async   getCustomer(query, cb) {  //查询客户列表


            var namePy = await webPy.firstLetter(query)


            var data = {
                "$or": [
                    { name: { $regex: query } },
                    { namePy: { $regex: namePy } }
                ]
            }
            //  console.log(JSON.stringify(data));

            this.loading = true;
            axios.post("/a", {
                class: "customer",
                para: "getCustomerList",
                j: {
                    data: data

                }

            }).then((res) => {

                this.loading = false;

                var list = res.data.list;
                if (res.data.list) {
                    list.forEach(function (customer) {
                        customer.value = customer.name;

                    }, this);

                    console.dir(list);
                    cb(list)
                }


            });


        },

        //获取用户列表
        getCustomerOrderList() {

            this.listLoading = true;
            NProgress.start();
            axios.post("/a", {
                class: "customerOrder",
                para: "getCustomerOrderList",
                j: {}

            }).then((res) => {
                res.data.list.forEach(function (element) {
                    element.show = false
                }, this);
                this.customerOrderList = res.data.list;



                this.totalPage = res.data.totalPage;
                this.listLoading = false;
                NProgress.done();


            });
        },
        //点击新增按钮
        addCustomerOrder() {





            this.fmtCurrObj();


            this.ShowSave = true;
            this.fmtTabs();
            this.currTab = "1";
        },


        //显示编辑界面  /获取订单
        toSaveCustomerOrder: function (row) {

            this.currTab = "1";
            this.ShowSave = true;
            this.currObj._id = row._id
            console.log(row._id);
        },
        getCustomerOrder: function () {

            if (this.currObj._id) {
                setTimeout(() => {

                    var ld = this.$loading({
                        fullscreen: false, text: "努力加载订单信息",
                        target: ".el-tabs"
                    })
                    setTimeout(() => {
                        axios.post("/a", {
                            class: "customerOrder",
                            para: "getCustomerOrder",
                            j: {
                                _id: this.currObj._id
                            }

                        }).then((res) => {

                            if (!res.data.info.customerName) {
                                res.data.info.customerName = "";

                            }

                            this.fmtCurrObj(res.data.info);

                            this.getTaskList()   //加载任务列表


                            if (res.data.customerInfo) {
                                this.customerSelList = [

                                    {
                                        name: res.data.customerInfo.name,
                                        _id: res.data.customerInfo._id

                                    }
                                ]

                            }

                            this.fmtTabs();
                            ld.close();
                        });
                    }, 300);

                }, 100);

            }
            else {

            }



        },

        //保存订单
        saveCustomerOrder: function () {
            this.currObj.companyCode = localStorage.companyCode;
            //   alert(JSON.stringify(this.currObj.fileList));
            axios.post("/a", {
                class: "customerOrder",
                para: "saveCustomerOrder",
                j: this.currObj

            }).then((res) => {
                if (res.data.re == "ok") {
                    this.ShowSave = false;
                    this.getCustomerOrderList();
                } else {
                    alert(JSON.stringify(res.data));
                }
            });
        },
        fmtCurrObj: function (obj) {


            Vue.set(this, "currObj", dCustomerOrder.fmtCustomerOrder(obj))


        },
        //新增节点
        addNode: function () {

        },
        toSaveNode: function (nodeObj) {

            switch (this.currTab) {
                case "3":
                    this.currFlow = this.currObj.flow.proof;
                    break;
                case "5":
                    this.currFlow = this.currObj.flow.bulk;
                    break;


            }


            if (nodeObj) {


                // if (nodeObj.id == "root") {
                //     return;
                // }

                this.currNodeObj = nodeObj;
            }

            if (!this.currNodeObj.taskClassId) {

                this.currNodeObj.taskClassId = 'default';
            }

            this.ShowSaveNode = true;
        },
        saveNode: function () {


            var type = 'proof';

            if (this.currTab == "2" || this.currTab == "3") {


            }
            else {
                type = 'bulk'
            }

            if (!this.currFlow.nodeList) {
                this.currFlow.nodeList = [];

            }
            if (!this.currNodeObj.id) {
                this.currNodeObj.id = moment().utcOffset(-8).format("YYMMDDHHmmssSSS");
            }
            if (!this.currNodeObj.rely) {

                this.currNodeObj.rely = [];
            }

            var isAdd = true;
            this.currFlow.nodeList.forEach(function (node) {

                if (this.currNodeObj.id == node.id) {
                    //当前节点的ID已经存在了. 就不是新增了
                    isAdd = false;
                }

            }, this);
            if (isAdd) {
                //如果是新增, 就增加一条
                this.currFlow.nodeList.push(this.currNodeObj);
            }





            this.ShowSaveNode = false;
            this.$message({
                message: '节点已变更, 请不要忘记保存流程',
                type: 'success'
            });




            //   this.joinData();
        },
        fmtTabs: function () {


            this.tabs = [];
            this.tabs.push({
                title: "基础信息",
                name: "10"

            })
            if (this.currObj.openProof) {
                this.tabs.push({
                    title: "打样详情",
                    name: "20"

                })
                this.tabs.push({
                    title: "打样流程",
                    name: "25"

                })

            }

            if (this.currObj.openBulk) {
                this.tabs.push({
                    title: "大货详情",
                    name: "50"

                })
                this.tabs.push({
                    title: "大货流程",
                    name: "55"

                })

            }


            this.tabs.push({
                title: "订单任务",
                name: "70"

            })
            this.tabs.push({
                title: "订单日志",
                name: "80"

            })
        },

        openProof: function (b) {

            this.currObj.openProof = b;
            this.fmtTabs();
        },
        openBulk: function (b) {
            this.currObj.openBulk = b;
            this.fmtTabs();
        },
        orderTabSel: function (params) {

        },
        addNodeMember(member, type) {
            console.log(type);
        },
        removeNodeMember(member, type) {
            console.log(type);
        },



        //执行节点
        exeCustomerOrderFlow: function (node) {

            console.log("执行节点");
            console.dir(node);
            var flowClassId = null

            switch (this.currTab) {
                case "3":
                    flowClassId = "proof"
                    break;
                case "5":
                    flowClassId = "bulk"

                    break;

                default:
                    throw "flowClassId未识别"

            }
            axios.post("/a", {
                class: "customerOrder",
                para: "exeCustomerOrderFlow",
                j: {
                    flowClassId: flowClassId,
                    nodeId: node.id,
                    customerOrderId: this.currObj._id,
                    companyCode: localStorage.companyCode

                }

            }).then((res) => {
                if (res.data.re == "ok") {
                    console.log("执行成功!");
                    this.getCustomerOrder()
                } else {

                }
            });
        },
        shuaxinOrder() {

            this.getCustomerOrder();
        },
        show(o) {

            showCustomerOrderId = o._id

        },
        fileChange() {



        },
        selContract(contractInfo) {


            Vue.set(this.currObj, "contractInfo", contractInfo)
        },
        async querySearchContract(query, cb) {
            var data = {
                "$or": [
                    { name: { $regex: query } },
                    { namePy: { $regex: await webPy.firstLetter(query) } },
                    { code: { $regex: query } }
                ]
            }
            //  console.log(JSON.stringify(data));
            if (query !== '') {
                this.loading = true;
                axios.post("/a", {
                    class: "contract",
                    para: "getContractList",
                    j: {
                        data: data

                    }

                }).then((res) => {

                    this.loading = false;

                    var list = res.data.list;

                    list.forEach(function (member) {
                        member.value = member.name;

                    }, this);
                    cb(list)

                });

            }

        },
        getTaskList() {
            //加载订单任务
            var nodeIdArray = [];

            if (this.currObj.openBulk) {
                this.currObj.flow.bulk.nodeList.forEach(function (node) {
                    nodeIdArray.push(node.id)

                }, this);
            }
            if (this.currObj.openProof) {
                this.currObj.flow.proof.nodeList.forEach(function (node) {
                    nodeIdArray.push(node.id)
                }, this);
            }





            axios.post("/a", {
                class: "task",
                para: "getTaskList",
                j: {
                    //提交form时提交参数
                    data: {
                        customerOrderId: this.currObj._id,
                        nodeId: { $in: nodeIdArray }

                    }
                }
            }).then((res) => {

                if (res.err) {
                    this.message({
                        message: res.err,
                        type: 'error'  //success  warning  info  error
                    });
                }
                else {
                    this.taskList = res.data.list

                }

            });
        },
        toOfferPrint: function (customerOrderId, flowClassId) {

            this.currCustomerOrderId = customerOrderId
            this.currFlowClassId = flowClassId
            this.showOfferPrint = true

        },
        toTechnologyPrint: function (customerOrderId, flowClassId) {
            this.currCustomerOrderId = customerOrderId
            this.currFlowClassId = flowClassId
            this.showTechnologyPrint = true
        }



        //新增
    },

    watch: {



    },


    mounted() {
        this.getCustomerOrderList();
        // this.fmtCurrObj();

    },

    components: {

        flowNodeList,
        flowNode,
        colorSizeData,
        imgSel,
        customerOrderShow,
        taskInfo,
        file,
        offerPrint,
        technologyPrint

    }

}